// Load the http module to create an http server.
var http = require('http');
var url  = require('url');
var winston = require('winston');
var parser = require('ua-parser');
var https = require('https');
var fs = require('fs');

// Configure Winston (Logging)
//winston.add(winston.transports.File, { filename: './rum.log', json: false });
winston.remove(winston.transports.Console);
options = {};
options.splunkHost = "10.30.196.20"
options.splunkPort = 7000;
winston.add(require('winston-splunk').splunk, options);

function getClientIp(req) {
  var ipAddress;
  // Amazon EC2 / Heroku workaround to get real client IP
  var forwardedIpsStr = req.header('x-forwarded-for');
  if (forwardedIpsStr) {
    // 'x-forwarded-for' header may return multiple IP addresses in
    // the format: "client IP, proxy 1 IP, proxy 2 IP" so take the
    // the first one
    var forwardedIps = forwardedIpsStr.split(',');
    ipAddress = forwardedIps[0];
  }
  if (!ipAddress) {
    // Ensure getting client IP address still works in
    // development environment
    ipAddress = req.connection.remoteAddress;
  }
  return ipAddress;
};

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {

  var obj = url.parse(request.url, true).query;
  obj["ua_raw"] = parser.parse(request.headers['user-agent']);
  obj["ip"] = request.connection.remoteAddress;

  // Convert object to string for logging
//  var string = JSON.stringify(obj);

  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello World\n");
//  winston.log('info', string );
  winston.log('info', obj);
});

// Listen on port 7000, IP defaults to 127.0.0.1
server.listen(7000);

var ssloptions = {
  key: fs.readFileSync('./edirlinux_aib_pri.key'),
  cert: fs.readFileSync('./edirlinux_aib_pri.cer')
};
var sslserver = https.createServer(ssloptions, function (request, response) {

  var obj = url.parse(request.url, true).query;
  obj["ua_raw"] = parser.parse(request.headers['user-agent']);
  obj["ip"] = request.connection.remoteAddress;

  // Convert object to string for logging
//  var string = JSON.stringify(obj);

  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello World\n");
//  winston.log('info', string );
  winston.log('info', obj);
});
sslserver.listen(8000);

// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:7000/ and https://127.0.0.1:8000");
